import axios from "axios";
import { ElMessage } from "element-plus";
import store from "@/store";
const http = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
});

// 请求拦截
http.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      //如果有token的话一定要携带上  携带token到后端进行 比对授权
      config.headers.Authorization = `Bearer ${store.getters.token}`;
      console.log(config);
    }
    return config;
  },
  (err) => {
    console.log("请求拦截器没有配置成功");
  }
);
// 响应拦截
http.interceptors.response.use(
  (res) => {
    const { info } = res.data;
    if (info == "success") {
      return res.data;
    } else {
      ElMessage.error(info);
      if (res.data.code == "403") {
        store.dispatch("/user/logout");
      }
    }
  },
  function (error) {
    return Promise.reject(error);
  }
);

export default http;
